package cn.com.nes.common.baiduface;

import java.util.Calendar;
import java.util.Date;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.node.ObjectNode;

public class AccessTokenManager {

	private String refreshToken;
	private Date expiresIn;
	private String[] scope;
	private String sessionKey;
	private String accessToken;
	private String sessionSecret;
	
	private final String clientId;
	private final String clientSecret;
	
	public AccessTokenManager(String clientId, String clientSecret) {
		Assert.hasLength(clientId);
		Assert.hasLength(clientSecret);
		this.clientId = clientId;
		this.clientSecret = clientSecret;
	}
	
	private synchronized void checkToken() {
		if(expiresIn == null || expiresIn.after(new Date())) {
			ObjectNode result = BaiduApis.getToken(clientId, clientSecret);
			if(result.has("error")) {
				throw new RuntimeException(result.get("error").asText() + ": " + result.get("error_description").asText());
			}
			if(result.has("refresh_token")) {
				refreshToken = result.get("refresh_token").asText();
			}
			if(result.has("expires_in")) {
				int expiresIn = result.get("expires_in").asInt();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.add(Calendar.SECOND, expiresIn - 86400);
				this.expiresIn = calendar.getTime();
			}
			if(result.has("session_key")) {
				sessionKey = result.get("session_key").asText();
			}
			if(result.has("access_token")) {
				accessToken = result.get("access_token").asText();
			}
			if(result.has("scope")) {
				String scope = result.get("scope").asText();
				if(StringUtils.hasText(scope)) {
					this.scope = scope.split(" ");
				} else {
					this.scope = new String[0];
				}
			}
			if(result.has("session_secret")) {
				sessionSecret = result.get("session_secret").asText();
			}
		}
	}

	public synchronized String getRefreshToken() {
		checkToken();
		return refreshToken;
	}

	public synchronized Date getExpiresIn() {
		checkToken();
		return expiresIn;
	}

	public synchronized String[] getScope() {
		checkToken();
		return scope;
	}

	public synchronized String getSessionKey() {
		checkToken();
		return sessionKey;
	}

	public synchronized String getAccessToken() {
		checkToken();
		return accessToken;
	}

	public synchronized String getSessionSecret() {
		checkToken();
		return sessionSecret;
	}
	
	
	
}
